import {Component, OnInit} from '@angular/core';
import {FormArray, FormBuilder, FormGroup, Validators} from "@angular/forms";

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {
  myForm: FormGroup

  constructor(
    private fb: FormBuilder,
  ) {
    this.myForm = this.fb.group({
      username: ['', Validators.required],
      password: ['', Validators.required],
      address: this.fb.group({
        city: [''],
        street: [''],
      }),
      education: this.fb.array([
        this.school,
      ])
    })
  }

  ngOnInit(): void {
    this.myForm.patchValue({
      username: 'test-username',
      password: 'test-username',
      address: {
        city: 'test-city',
        street: 'test-street'
      },
      education: [
        {school: 'test-school1'}
      ]
    })
  }

  get education() {
    return this.myForm.get('education') as FormArray
  }

  get school() {
    return this.fb.group({
      school: ['', Validators.required]
    })
  }

  addEducation() {
    this.education.push(this.school)
  }

  removeEducation(idx: number) {
    this.education.removeAt(idx)
  }

  submit() {
    console.log('form value', this.myForm.getRawValue())
  }

}
